<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2022-04-22
 * Time: 14:10:35
 * Info:
 */

namespace app\common\model;

class LoginLog extends Common
{

    public static function addRecord($loginDevice)
    {
        if (empty($loginDevice)) {
            return false;
        }

        $update               = [];
        $update['user_id']    = $loginDevice['user_id'] ?? 0;
        $update['user_name']  = $loginDevice['user_name'] ?? '';
        $update['ip_address'] = $loginDevice['ip_address'] ?? '';
        $update['country']    = $loginDevice['country'] ?? '';
        $update['area']       = $loginDevice['area'] ?? '';
        $update['city']       = $loginDevice['city'] ?? '';
        $update['isp']        = $loginDevice['isp'] ?? '';
        $update['desc']       = $loginDevice['desc'] ?? '';

        self::create($update);

        return true;
    }

    /**
     * 查询登录失败错误次数
     * @return void
     */
    public static function select_logs($ip)
    {
        //N分钟内的数据
        $dTime = time() - 60 * get_env('HUICMF.login_failure_min');
        //查询的次数
        $times = get_env('HUICMF.login_failure_times');
        $count = self::where(['ip_address' => $ip, 'status' => 0])->where('create_time', '>', $dTime)->count();
        //N分钟内一个ip只能错误N次。如果超过此ip将禁止访问（加入config的admin_prohibit_ip中。）
        if ($count >= $times) {
            //写入ip锁定
            Config::update_prohibit_ip($ip);

            return false;
        }

        return true;
    }

}
